// pages/audio-list/audio-list.js
Page({
  data: {
    // 分类数据
    categories: ['最近', '英文', '中文', '收藏'],
    currentCategory: '最近',
    
    // 音频列表
    audioList: [],
    currentAudioId: null,
    isPlaying: false,
    currentAudioIndex: 0,
    
    // 播放控制
    playMode: 'sequence', // sequence, loop, random
    timerMinutes: 0, // 定时关闭时间（分钟）
    
    // 播放器状态
    showTimerModal: false,
    
    // 模拟数据
    mockAudioData: {
      '最近': [
        { id: 1, title: '小兔子乖乖', coverUrl: '/images/book.png', source: '中文儿歌', duration: '2:30', type: 'zh' },
        { id: 2, title: 'ABC Song', coverUrl: '/images/book-cn.png', source: '英文儿歌', duration: '1:45', type: 'en' },
        { id: 3, title: '两只老虎', coverUrl: '/images/calendar.png', source: '中文儿歌', duration: '2:15', type: 'zh' }
      ],
      '英文': [
        { id: 2, title: 'ABC Song', coverUrl: '/images/book-cn.png', source: '英文儿歌', duration: '1:45', type: 'en' },
        { id: 4, title: 'Twinkle Twinkle', coverUrl: '/images/users.png', source: '英文儿歌', duration: '2:00', type: 'en' },
        { id: 5, title: 'Old MacDonald', coverUrl: '/images/user.png', source: '英文儿歌', duration: '3:20', type: 'en' }
      ],
      '中文': [
        { id: 1, title: '小兔子乖乖', coverUrl: '/images/book.png', source: '中文儿歌', duration: '2:30', type: 'zh' },
        { id: 3, title: '两只老虎', coverUrl: '/images/calendar.png', source: '中文儿歌', duration: '2:15', type: 'zh' },
        { id: 6, title: '小星星', coverUrl: '/images/users.png', source: '中文儿歌', duration: '1:50', type: 'zh' }
      ],
      '收藏': [
        { id: 1, title: '小兔子乖乖', coverUrl: '/images/book.png', source: '中文儿歌', duration: '2:30', type: 'zh' },
        { id: 2, title: 'ABC Song', coverUrl: '/images/book-cn.png', source: '英文儿歌', duration: '1:45', type: 'en' }
      ]
    }
  },

  onLoad: function (options) {
    this.loadAudioList();
    this.initAudioContext();
  },

  onShow: function () {
    // 恢复播放状态
    this.restorePlayState();
  },

  // 返回上一页
  onBack: function () {
    wx.navigateBack({
      delta: 1
    });
  },

  // 搜索功能
  onSearch: function () {
    wx.showToast({
      title: '搜索功能开发中',
      icon: 'none'
    });
  },

  // 阻止事件冒泡
  stopPropagation: function () {
    // 空函数，用于阻止事件冒泡
  },

  // 加载音频列表
  loadAudioList: function () {
    const category = this.data.currentCategory;
    const audioList = this.data.mockAudioData[category] || [];
    this.setData({
      audioList: audioList
    });
  },

  // 初始化音频上下文
  initAudioContext: function () {
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.onPlay(() => {
      this.setData({ isPlaying: true });
    });
    this.audioContext.onPause(() => {
      this.setData({ isPlaying: false });
    });
    this.audioContext.onEnded(() => {
      this.playNext();
    });
    this.audioContext.onError((res) => {
      wx.showToast({
        title: '播放失败，请稍后再试',
        icon: 'none'
      });
    });
  },

  // 分类切换
  onCategoryTap: function (e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      currentCategory: category
    });
    this.loadAudioList();
  },

  // 播放全部
  onPlayAll: function () {
    if (this.data.audioList.length === 0) {
      wx.showToast({
        title: '暂无音频内容',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      currentAudioIndex: 0,
      currentAudioId: this.data.audioList[0].id
    });
    this.playAudio(this.data.audioList[0]);
  },

  // 播放单个音频
  onAudioTap: function (e) {
    const audio = e.currentTarget.dataset.audio;
    const index = e.currentTarget.dataset.index;
    
    this.setData({
      currentAudioId: audio.id,
      currentAudioIndex: index
    });
    
    this.playAudio(audio);
  },

  // 播放音频
  playAudio: function (audio) {
    // 模拟音频播放
    this.audioContext.src = `https://example.com/audio/${audio.id}.mp3`;
    this.audioContext.play();
    
    wx.showToast({
      title: `正在播放：${audio.title}`,
      icon: 'none',
      duration: 1500
    });
  },

  // 播放/暂停
  onPlayPause: function () {
    if (this.data.isPlaying) {
      this.audioContext.pause();
    } else {
      this.audioContext.play();
    }
  },

  // 上一首
  onPrevious: function () {
    if (this.data.audioList.length === 0) return;
    
    let index = this.data.currentAudioIndex - 1;
    if (index < 0) {
      index = this.data.audioList.length - 1;
    }
    
    const audio = this.data.audioList[index];
    this.setData({
      currentAudioIndex: index,
      currentAudioId: audio.id
    });
    this.playAudio(audio);
  },

  // 下一首
  onNext: function () {
    if (this.data.audioList.length === 0) return;
    
    let index = this.data.currentAudioIndex + 1;
    if (index >= this.data.audioList.length) {
      index = 0;
    }
    
    const audio = this.data.audioList[index];
    this.setData({
      currentAudioIndex: index,
      currentAudioId: audio.id
    });
    this.playAudio(audio);
  },

  // 自动播放下一首
  playNext: function () {
    if (this.data.playMode === 'loop') {
      // 单曲循环，重新播放当前音频
      const currentAudio = this.data.audioList[this.data.currentAudioIndex];
      this.playAudio(currentAudio);
    } else {
      // 播放下一首
      this.onNext();
    }
  },

  // 删除音频
  onDeleteAudio: function (e) {
    const audioId = e.currentTarget.dataset.audioId;
    const index = e.currentTarget.dataset.index;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个音频吗？',
      success: (res) => {
        if (res.confirm) {
          const audioList = [...this.data.audioList];
          audioList.splice(index, 1);
          
          this.setData({
            audioList: audioList
          });
          
          wx.showToast({
            title: '已删除',
            icon: 'success'
          });
        }
      }
    });
  },

  // 显示定时设置
  onShowTimer: function () {
    this.setData({
      showTimerModal: true
    });
  },

  // 隐藏定时设置
  onHideTimer: function () {
    this.setData({
      showTimerModal: false
    });
  },

  // 设置定时
  onSetTimer: function (e) {
    const minutes = e.currentTarget.dataset.minutes;
    this.setData({
      timerMinutes: minutes,
      showTimerModal: false
    });
    
    if (minutes > 0) {
      wx.showToast({
        title: `${minutes}分钟后自动停止`,
        icon: 'none'
      });
      
      // 启动定时器
      setTimeout(() => {
        this.audioContext.pause();
        this.setData({
          isPlaying: false,
          timerMinutes: 0
        });
        wx.showToast({
          title: '播放已定时停止',
          icon: 'none'
        });
      }, minutes * 60 * 1000);
    }
  },

  // 切换播放模式
  onTogglePlayMode: function () {
    const modes = ['sequence', 'loop', 'random'];
    const currentIndex = modes.indexOf(this.data.playMode);
    const nextIndex = (currentIndex + 1) % modes.length;
    const newMode = modes[nextIndex];
    
    this.setData({
      playMode: newMode
    });
    
    const modeNames = {
      'sequence': '顺序播放',
      'loop': '单曲循环',
      'random': '随机播放'
    };
    
    wx.showToast({
      title: modeNames[newMode],
      icon: 'none'
    });
  },

  // 恢复播放状态
  restorePlayState: function () {
    // 从本地存储恢复播放状态
    const playState = wx.getStorageSync('audioPlayState');
    if (playState) {
      this.setData({
        currentAudioId: playState.audioId,
        currentAudioIndex: playState.audioIndex,
        isPlaying: playState.isPlaying
      });
    }
  },

  // 保存播放状态
  savePlayState: function () {
    const playState = {
      audioId: this.data.currentAudioId,
      audioIndex: this.data.currentAudioIndex,
      isPlaying: this.data.isPlaying
    };
    wx.setStorageSync('audioPlayState', playState);
  },

  onUnload: function () {
    // 保存播放状态
    this.savePlayState();
    
    // 释放音频资源
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  }
}); 